package com.ts.oss.controller;

import com.ts.common.RandomUtils;
import com.ts.oss.client.SmsClient;
import com.ts.oss.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/lxb/sms")
@Api(tags = "短信管理")
public class ApiSmsController {
    @Resource
    private SmsService smsService;

    @Resource
    SmsClient smsClient;

    @Resource
    RedisTemplate redisTemplate;


    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public Map<String,Object> SmsSend(
            @ApiParam(value = "手机号",required = true)
            @PathVariable String mobile
    ){
        //判断手机号是否已经被注册
        Map<String, Object> byMobile = smsClient.getByMobile(mobile);
        boolean b= (boolean) byMobile.get("data");
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();


        if(!b){
//            1.生成随机数
            String fourBitRandom = RandomUtils.getFourBitRandom();
            smsService.sendMessage(mobile,fourBitRandom);
            redisTemplate.opsForValue().set("lxb:sms:code:"+mobile,fourBitRandom,5, TimeUnit.MINUTES);
            stringObjectHashMap.put("code",0);
            stringObjectHashMap.put("message","短信发送成功");


        }
        else
        {
            stringObjectHashMap.put("code",404);
            stringObjectHashMap.put("message","短信发送失败");
            //该手机号已经被认证过
        }


        return stringObjectHashMap;

    }


}
